package com.haizhi.crm.common.context;

import com.haizhi.crm.common.util.LocalHost;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.springframework.core.env.Environment;
import org.springframework.util.ResourceUtils;

import java.io.FileNotFoundException;
import java.text.MessageFormat;

/**
 * Created by chengmo on 2017/11/07.
 */
public class Resource {

    private final static LocalHost localHost = new LocalHost();

    public static String getIPAndPort() {
        return getIP() + ":" + getPort();
    }

    public static String getIP() {
        return localHost.getIp();
    }

    public static int getPort() {
        return NumberUtils.toInt(SpringContext.getProperty("server.port" ));
    }

    public static String getActiveProfile() {
        Environment env = SpringContext.getEnv();
        String activeProfile = env.getActiveProfiles()[0];
        return MessageFormat.format("application-{0}.properties", activeProfile);
    }

    public static String getPath(String resourceLocation) {
        try {
            return ResourceUtils.getURL("classpath:" + resourceLocation).getPath();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        return "";
    }

    public static String getJarPath() {
        String path = getResourcePath();
        if (path.contains("/target/" )) {
            path = StringUtils.substringBefore(path, "target/" );
            return path + "target/";
        } else if (path.endsWith("/lib/" )) {
            return StringUtils.substringBefore(path, "lib/" );
        }
        return path;
    }

    public static String getPath() {
        String path = getResourcePath();
        if (path.contains("/target/" )) {
            if (path.contains("/test-classes/" )) {
                return path.replace("test-classes", "classes" );
            }
        } else {
            return path.replace("/lib/", "/conf/" );
        }
        return path;
    }

    private static String getResourcePath() {
        String path = Resource.class.getResource("/" ).getPath();
        return path;
    }

    public static void main(String[] args) throws FileNotFoundException {
        //System.out.println(Resource.getPath("mysql.sql"));
        System.out.println(Resource.getPath());
        System.out.println(Resource.getJarPath());
    }
}
